package com.blb.thread;

/**
 * 线程死锁
 * 是什么？两个线程或多个线程，相互持有对方的锁，又都需要对方的锁，形成循环等待，导致程序卡死
 * 什么情况下可能出现： 出现嵌套的同步代码块
 * 解决方法：不要出现同步代码块的嵌套
 */
public class DeadLockDemo {

    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public void test1(){
        //同步代码块的嵌套
        synchronized (lock1){
            System.out.println(Thread.currentThread().getName()+"持有lock1,需要lock2");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock2){
                System.out.println(Thread.currentThread().getName()+"执行完了");
            }
        }
    }

    public void test2(){
        //同步代码块的嵌套
        synchronized (lock2){
            System.out.println(Thread.currentThread().getName()+"持有lock2,需要lock1");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lock1){
                System.out.println(Thread.currentThread().getName()+"执行完了");
            }
        }
    }

    public static void main(String[] args) {
        DeadLockDemo deadLockDemo = new DeadLockDemo();
        new Thread(() -> {
            deadLockDemo.test1();
        }).start();
        new Thread(() -> {
            deadLockDemo.test2();
        }).start();
    }
}
